package cn.dyw.engine.web.api;

import cn.dyw.engine.core.exception.EngineExecException;
import cn.dyw.engine.core.exec.ReportResult;
import cn.dyw.engine.web.api.rq.ReportDefinitionRq;
import cn.dyw.engine.web.api.rq.ReportSaveRq;
import cn.dyw.engine.web.api.rs.ReportRs;
import cn.dyw.engine.web.api.rs.Result;
import cn.dyw.engine.web.db.service.impl.ReportDefinitionServiceImpl;
import cn.dyw.engine.web.service.ReportExecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 报表定义和执行api
 *
 * @author dyw770
 * @since 2021-08-06
 */
@RestController
@RequestMapping("/custom")
public class CustomReportApi {

    @Autowired
    private ReportExecService reportExecService;

    @Autowired
    private ReportDefinitionServiceImpl reportDefinitionServiceImpl;

    /**
     * 执行自定义报表
     *
     * @param rq 参数
     * @return 执行的结果
     *
     * @throws EngineExecException 执行的异常
     */
    @PostMapping("/exec")
    public Result<ReportResult> exec(@RequestBody ReportDefinitionRq rq) throws EngineExecException {
        ReportResult result = reportExecService.reportExec(rq);
        return Result.createSuccess("查询成功", result);
    }


    /**
     * 保存自定义报表
     *
     * @param rq 参数
     * @return 保存结果
     *
     * @throws EngineExecException 保存失败的异常
     */
    @PostMapping("/save")
    public Result<String> save(@RequestBody ReportSaveRq rq) throws EngineExecException {
        reportDefinitionServiceImpl.save(rq);
        return Result.createSuccess("保存成功", "保存成功");
    }

    /**
     * 获取自定义报表
     *
     * @param id id
     * @return 结果
     *
     * @throws EngineExecException 保存失败的异常
     */
    @GetMapping("/{id}")
    public Result<ReportRs> one(@PathVariable("id") int id) throws EngineExecException {
        ReportRs one = reportDefinitionServiceImpl.one(id);
        return Result.createSuccess("查询成功", one);
    }

    /**
     * 更新自定义报表
     *
     * @param id id
     * @param rq 参数
     * @return 结果
     *
     * @throws EngineExecException 保存失败的异常
     */
    @PostMapping("/{id}")
    public Result<String> update(@PathVariable("id") int id, @RequestBody ReportSaveRq rq) throws EngineExecException {
        reportDefinitionServiceImpl.update(rq, id);
        return Result.createSuccess("更新成功", "更新成功");
    }
}
